from flask import Blueprint, request, jsonify
from app.services.auth_service import AuthService
from app.schemas import UserSchema, LoginSchema, ResetPasswordSchema
from marshmallow import ValidationError

auth_bp = Blueprint('auth', __name__)
user_schema = UserSchema()
login_schema = LoginSchema()
reset_password_schema = ResetPasswordSchema()

@auth_bp.route('/register', methods=['POST'])
def register():
    try:
        # 获取原始请求数据
        raw_data = request.get_json()
        if not raw_data:
            return jsonify({'error': 'No input data provided'}), 400

        # 验证请求数据
        data = user_schema.load(raw_data)
        
        # 调用服务层处理业务逻辑
        user = AuthService.register_user(
            username=data['username'],
            email=data['email'],
            password=data['password']
        )
        
        return jsonify({
            'message': 'User registered successfully'
        }), 201
        
    except ValidationError as err:
        return jsonify({'error': 'Validation error'}), 400
    except ValueError as err:
        return jsonify({'error': str(err)}), 400
    except Exception as e:
        from flask import current_app
        current_app.logger.error(f"Registration failed: {str(e)}")
        return jsonify({'error': 'Registration failed'}), 500

@auth_bp.route('/login', methods=['POST'])
def login():
    try:
        # 验证请求数据
        data = login_schema.load(request.get_json())
        
        # 调用服务层处理业务逻辑
        token = AuthService.login_user(
            username=data['username'],
            password=data['password']
        )
        
        return jsonify({'access_token': token}), 200
        
    except ValidationError as err:
        return jsonify({'error': 'Validation error', 'messages': err.messages}), 400
    except ValueError as err:
        return jsonify({'error': str(err)}), 401
    except Exception:
        return jsonify({'error': 'Internal server error'}), 500

@auth_bp.route('/reset-password', methods=['POST'])
def reset_password():
    try:
        # 验证请求数据
        data = reset_password_schema.load(request.get_json())
        
        # 调用服务层处理业务逻辑
        success = AuthService.reset_password(
            username=data['username'],
            email=data['email'],
            new_password=data['new_password']
        )
        
        if not success:
            return jsonify({'error': 'Username and email do not match'}), 400
            
        return jsonify({
            'message': 'Password has been reset successfully'
        }), 200
        
    except ValidationError as err:
        return jsonify({'error': 'Validation error', 'messages': err.messages}), 400
    except Exception:
        return jsonify({'error': 'Internal server error'}), 500
